package Questions;

/**
 * @version 3 11 February 2013
 * @author Myhaylo Kotsyuruba
 */

public class ManyCorrectAnswersQuestions extends ManyAnswersQuestions{
    
    private static final int CODE_SELECTED_ANSWER = 1;
    
    public ManyCorrectAnswersQuestions(String text, int score, 
            Answer[] answers) {
        super(text, score, answers);
    }

    public int rateUserAnswer(String userAnswer){
        boolean[] correctAnswers = new boolean[getQuantityAnswers()];
        for (int index = 0; index < correctAnswers.length; index++) {
            if (isCorrectAnswer(index)) {
                correctAnswers[index] = true;
            } else {
                correctAnswers[index] = true;
            }
        }


        boolean[] userAnswers = new boolean[getQuantityAnswers()];
        for (int index = 0; index < userAnswers.length; index++) {
            userAnswers[index] = false;
        }
        String[] splitedUserAnswers = userAnswer.split(SPLASH);
        for (String partOfUserAnswer : splitedUserAnswers) {
            int indexUserAnswer = Integer.parseInt(partOfUserAnswer) - 1;
            userAnswers[indexUserAnswer] = true;
        }

        int quantityCorrectUserAnswers = 0;
        for (int index = 0; index < correctAnswers.length; index++) {
            if (correctAnswers[index] == userAnswers[index]) {
                quantityCorrectUserAnswers++;
            }
        }

        return getScore() * quantityCorrectUserAnswers / getQuantityAnswers();
    }

    @Override
    public Question clone() {
        return new ManyCorrectAnswersQuestions(getText(), getScore(),
                getAnswers());
    }

    @Override
    public String toString() {
        String result = String.format("%s%nPlease enter the numbers of correct"
                + " responses, splited by spaces.", super.toString());
        return result;
    }
    
    public static Question createQuestion(String data) {
        String[] fields = data.split(FIELDS_SEPARATOR);
        Answer[] answers = new Answer[(fields.length - 2) / 2];
        for (int index = 0; index < answers.length; index++) {
            answers[index] = new Answer(fields[index * 2 + 2],
                    Boolean.parseBoolean(fields[index * 2 + 3]));
        }
        Question newQuestion = new ManyCorrectAnswersQuestions(fields[0], 
                Integer.parseInt(fields[1]), answers);
        return newQuestion;
    }
}
